package com.conan.app.dailyflickr.provider;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.conan.app.dailyflickr.provider.Constants.PHOTO_TABLE;
import com.conan.app.dailyflickr.provider.Constants.WIDGET_TABLE;

public class DailyFlickrProvider extends ContentProvider{
	private static final int WIDGETS = 1;
	private static final int WIDGET_ID = 2;
	private static final int PHOTOS = 3;
	private static final int PHOTO_ID = 4;

	// Projector
	
	
	private static final UriMatcher sUriMatcher;
    static{
       sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
       sUriMatcher.addURI(Constants.PROVIDER_NAME, "widgets", WIDGETS);
       sUriMatcher.addURI(Constants.PROVIDER_NAME, "widgets/#", WIDGET_ID);
       
       sUriMatcher.addURI(Constants.PROVIDER_NAME, "photos", PHOTOS);
    }


	@Override
	public String getType(Uri uri) {
		switch (sUriMatcher.match(uri)) {
		
		 //---get all widgets---
	    case WIDGETS:
	       return "vnd.android.cursor.dir/vnd.conan2dailyflickr.widgets ";
	    //---get a particular widget---
	    case WIDGET_ID:                
	       return "vnd.android.cursor.item/vnd.conan2dailyflickr.widgets ";
	    case PHOTOS:                
		       return "vnd.android.cursor.item/vnd.conan2dailyflickr.photos ";
	    default:
	       throw new IllegalArgumentException("Unsupported URI: " + uri);
		}
	}

	private  DailyFlickrDBHelper mDBHelper;

	@Override
	public boolean onCreate() {
		  Context context = getContext();
		  mDBHelper = new DailyFlickrDBHelper(context);
		  return true;
	}

	private static final String TAG = "DailyFlickrProvider";
	@Override
	public Uri insert(Uri uri, ContentValues values) {
		//--- add a new widget ---
		long rowID = -1;
		SQLiteDatabase mWidgetDB = mDBHelper.getWritableDatabase();
		// --- if added successfully ----
		switch (sUriMatcher.match(uri)) {
			case WIDGETS:
				rowID = mWidgetDB.insert(Constants.TABLE_WIDGET_NAME, null, values);
				
				if(rowID > 0){
					Uri _uri = ContentUris.withAppendedId(Constants.CONTENT_URI, rowID);
					getContext().getContentResolver().notifyChange(_uri, null);
					
					return _uri;
				}
				break;
			case PHOTOS:
				rowID = mWidgetDB.insert(Constants.TABLE_PHOTO_NAME, null, values);
				if(rowID > 0){
					Uri _uri = ContentUris.withAppendedId(Constants.CONTENT_PHOTO_URI, rowID);
					getContext().getContentResolver().notifyChange(_uri, null);
					// Log.d("@le.nguyen", String.format("insert ... %s", _uri.toString()));
					return _uri;
				}
				break;
		}
		
		// if(mWidgetDB != null) mWidgetDB.close();
		throw new SQLException("Failed to insert row into " + uri);
	}
	
	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
		SQLiteDatabase mWidgetDB = mDBHelper.getWritableDatabase();
		
		int count = 0;
		
		switch (sUriMatcher.match(uri)) {
		case PHOTOS:
			count = mWidgetDB.delete(
					Constants.TABLE_PHOTO_NAME,
					where, 
					whereArgs);
			break;
		case WIDGETS:
			count = mWidgetDB.delete(
					Constants.TABLE_WIDGET_NAME,
					where, 
					whereArgs);
			break;
		case WIDGET_ID:
			String id = uri.getPathSegments().get(1);
			count = mWidgetDB.delete(
					Constants.TABLE_WIDGET_NAME,                        
					WIDGET_TABLE._ID + " = " + id + 
					(!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), 
					whereArgs);
			break;

		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		
		getContext().getContentResolver().notifyChange(uri, null);
		
		// if(mWidgetDB != null) mWidgetDB.close();
		return count;
		
	}
	
	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
			String sortOrder) {
		SQLiteDatabase mWidgetDB = mDBHelper.getWritableDatabase();
		
		SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

		
		int matcher = sUriMatcher.match(uri) ;
		// Log.d(TAG, "[query] = " + uri.toString() + " # " + matcher);
		
		if(matcher == PHOTOS){
			queryBuilder.setTables(Constants.TABLE_PHOTO_NAME);
			
			if (sortOrder==null || sortOrder=="")
				sortOrder = PHOTO_TABLE._NO;
			
		}else if(matcher == WIDGETS || matcher == WIDGET_ID){
			queryBuilder.setTables(Constants.TABLE_WIDGET_NAME);
			
			if (matcher == WIDGET_ID) {
				//---if getting a particular widget---
				queryBuilder.appendWhere(
						WIDGET_TABLE._ID + " = " + uri.getPathSegments().get(1));
			}   
			
			//---register to watch a content URI for changes---
			if (sortOrder==null || sortOrder=="")
				sortOrder = WIDGET_TABLE._ID;
	
		}
		
		Cursor c = queryBuilder.query(
				mWidgetDB, 
				projection, 
				selection, 
				selectionArgs, 
				null, 
				null, 
				sortOrder);
		c.setNotificationUri(getContext().getContentResolver(), uri);

		// if(mWidgetDB != null) mWidgetDB.close();
		return c;		
	}
	

	@Override
	public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
		SQLiteDatabase mWidgetDB = mDBHelper.getWritableDatabase();
		int count;

		switch (sUriMatcher.match(uri)) {
		case PHOTOS:
			count = mWidgetDB.update(
					Constants.TABLE_PHOTO_NAME,
					values,
					PHOTO_TABLE._NO + " = " + values.getAsInteger(PHOTO_TABLE._NO) + " AND " +
								PHOTO_TABLE._WIDGET_ID + " = " + values.getAsInteger(PHOTO_TABLE._WIDGET_ID)
								+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""),  
		               whereArgs);
			break;
		case WIDGETS:
			count = mWidgetDB.update(
					Constants.TABLE_WIDGET_NAME,
					values,
		               where, 
		               whereArgs);
			break;
		case WIDGET_ID:
			 count = mWidgetDB.update(
						Constants.TABLE_WIDGET_NAME, 
						values,
						WIDGET_TABLE._ID + " = " + uri.getPathSegments().get(1) + 
								(!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), 
		                whereArgs);
			break;

		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		
		getContext().getContentResolver().notifyChange(uri, null);
		// if(mWidgetDB != null) mWidgetDB.close();
		return count;
	}

	/*****************************************************************
	 ********************	DailyFlickrDBHelper	**********************
	 *****************************************************************/
	public class DailyFlickrDBHelper extends SQLiteOpenHelper{
		
		public DailyFlickrDBHelper(Context context) {
			super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			
			String table_widget = 
				"create table IF NOT EXISTS  " + 
				 Constants.TABLE_WIDGET_NAME + "(" +
				 WIDGET_TABLE._ID   + " INTEGER , " +
				 WIDGET_TABLE._PAGE + " INTEGER, " +
				 WIDGET_TABLE._DATE + " INTEGER, " +
				 
				 WIDGET_TABLE._URL  + " TEXT, " +
				 WIDGET_TABLE._TITLE  + " TEXT, " +
				 WIDGET_TABLE._LAYOUT + " INTEGER " +
				 "); ";
			
			db.execSQL(table_widget);
			
			String photo_widget = 
				"create table IF NOT EXISTS " + 
				 Constants.TABLE_PHOTO_NAME + "(" +
				 PHOTO_TABLE._ID	+	" TEXT, " +				 
				 WIDGET_TABLE._URL	+	" TEXT, " +
				 WIDGET_TABLE._TITLE	+	" TEXT, " +
				 PHOTO_TABLE._NO	+	" INTEGER, " +
				 PHOTO_TABLE._WIDGET_ID	+	" INTEGER " +
				 "); ";
			
			db.execSQL(photo_widget);
			
			
		}

		
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			int version = oldVersion;
			if(oldVersion !=  newVersion){
				// destroying old data during upgrade
				
				// db.execSQL("DROP TABLE IF EXISTS " + Constants.TABLE_PHOTO_NAME);				
				db.execSQL("DROP TABLE IF EXISTS " + Constants.TABLE_WIDGET_NAME);	
				db.execSQL("DROP TABLE IF EXISTS " + Constants.TABLE_PHOTO_NAME);
				onCreate(db);
			}				
		}
		
		
	}
}


